<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
    <style media="screen">
    body {background:black; text-align: center;}
    #c1 {background:white;}
    </style>
    <script>
    window.onload=function (){
      let oC=document.getElementById('c1');
      let oBtn=document.getElementById('btn1');
      let gd=oC.getContext('2d');

      let lastX,lastY;

      oC.onmousedown=function (ev){
        lastX=ev.offsetX;
        lastY=ev.offsetY;

        document.onmousemove=function (ev){
          gd.beginPath();

          gd.moveTo(lastX, lastY);
          gd.lineTo(ev.offsetX, ev.offsetY);

          gd.stroke();

          lastX=ev.offsetX;
          lastY=ev.offsetY;
        };

        document.onmouseup=function (){
          document.onmousemove=null;
          document.onmouseup=null;
        };
      };

      //上传
      oBtn.onclick=function (){
        //1.图片转成base64字符串
        let str=oC.toDataURL();

        //2.发给服务器
        let xhr=new XMLHttpRequest();

        xhr.open('post', '/upload_base64', true);
        xhr.send(encodeURIComponent(str));

        xhr.onreadystatechange=function (){
          if(xhr.readyState==4){
            alert(xhr.status);
          }
        };
      };

      //画进去
      let oF=document.getElementById('f1');
      let oBtn2=document.getElementById('btn2');

      oBtn2.onclick=function (){
        let reader=new FileReader();

        reader.onload=function (){
          let oImg=new Image();
          oImg.src=this.result;

          oImg.onload=function (){
            gd.drawImage(oImg, 0, 0);
          };
        };
        reader.readAsDataURL(oF.files[0]);
      };
    };
    </script>
  </head>
  <body>
    <input type="button" value="上传" id="btn1"><br>
    <input type="file" id="f1">
    <input type="button" value="画进去" id="btn2"><br>
    <canvas id="c1" width="400" height="300"></canvas>
  </body>
</html>
